<?php namespace App\Models;

use System\Model;

class Api extends Model
{
    protected $table = "api";
    protected $id = 'id';
    protected $fields = ['id', 'title', 'search', 'source', 'info', 'chapterList', 'chapter', 'static', 'rank', 'category', 'categoryBookList'];

    private $api;
    private $cache;

    public function __construct($id)
    {
        parent::__construct();
        $this->api = $this->find($id);
        $this->cache = new \System\Cache();
        $this->cache->setCache("API");
    }

    /**
     * @param string $type
     * @param array $param ["sp"=>,] url/sp?
     * @param string $path
     */
    public function getUrl($type, $param = "", $doCurl = true, $cache = true)
    {
        $url = $this->api[$type];
        if ($param) {
            if (isset($param['sp'])) {
                $url .= $param['sp'];
                unset($param['sp']);
            }
            $url .= \count($param) != 0 ? '?' . http_build_query($param, null, '&') : "";
        }

        if ($doCurl) {
            $curl = new \System\Curl();
            $result = $curl->url($url, $cache)->data();
            return json_decode($result, true);
        } else {
            return $url;
        }
    }
}
